<!-- eslint-disable vue/no-static-inline-styles -->
<template>

	<view class="projectDetail" :class="{'overflow': showFilter}">
		<view class="navBarTop">
			<global-nav-bar left-icon="back" title="项目详情" @setHeight="setHeight" :fixed="false"
				backgroundColor="#2C2C2C" color="#fff" @clickLeft="handleBack"></global-nav-bar>
		</view>
		<view class="header">
			<view class="header_content">
				<view class="top">
					<view class="left">
						<image src="@/static/images/index/build.svg" mode=""></image>
						<view class="title">
							<view>{{ projectMsg.name || '' }}</view>
							<view class="buildAddress " style="display:flex;align-items: center;"
								@click.stop="petName(projectMsg.buildingExt)"
								v-if="projectMsg.buildingExt && projectMsg.buildingExt.relationAliases && projectMsg.buildingExt.relationAliases.length">
								<view class="buildings">
									项目别名:{{ projectMsg.buildingExt.relationAliases.map(item => item.alias).join(",") }}
								</view>
								<view>
									<uni-icons :type="popupShowR ? 'arrowup' : 'arrowdown'" size="14"
										color="#999;"></uni-icons>
								</view>
							</view>
							<text style="font-size: 24rpx;color: #999;font-weight: normal;display: inline-block;">{{
								projectMsg.address ||'' }}</text>
						</view>
					</view>

					<view class="right" @click="toAddress(projectMsg)">
						<image src="@/static/images/locations.png" mode=""></image>
						<view>导航</view>
					</view>
				</view>
				<view class="msg">
					<view class="left">
						<image src="@/static/images/index/build.png" mode=""></image>
						{{ projectMsg.typeName || '' }}
						<view class="line"></view>
					</view>
					<view class="right">
						<view style="display: flex">
							<image src="@/static/images/index/total.png" mode=""></image>
							<view>总梯数:{{ projectMsg.eleTotal || 0 }}</view>
						</view>

						<view class="more" @click="toProjectDetail">更多信息
							<uni-icons color="#0091ff" size="16" type="arrowright"></uni-icons>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 保养计划 -->
		<view class="taskCard">
			<view class="topTitles">保养计划</view>
			<view class="top">
				<view class="topTitle" @click="todayClick">
					<text>{{ resCurrYM().currentYear }}</text>
					<image src="@/static/images/index/today.png" mode=""></image>
					<text>今天</text>
				</view>
				<view class="topRight">
					<view class="subTitle" @click="selectElevator">
						<image src="@/static/images/index/selectA.png" mode="" v-if="selectArr && selectArr.length">
						</image>
						<image src="@/static/images/index/selectD.png" mode="" v-else></image>
						<text :style="{ color: selectArr.length ? '#0091ff' : '#666' }"> {{
							!selectArr.length ? "全部梯" : `已筛选(${selectArr.length})`
						}}</text>

					</view>
					<view class="subLeft"></view>
					<view class="subTitle" @click="selectDown">
						<image src="@/static/images/download.png" mode="" />
						下载计划
					</view>
				</view>
				<!-- <view class="line"></view> -->
			</view>
			<view class="cardContent">
				<view class="cardContent_left">
					<weekcalendar style="width: 100%" ref="weekcalendar" @change="getRange" @pickDay="pickDay">
					</weekcalendar>
				</view>
				<view class="showdown"></view>
				<view class="cardContent_right" @click="toPlanDetail">
					<image src="@/static/images/more.png" mode="" />
					更多
				</view>
			</view>
		</view>
		<!--  -->

		<view class="tab_detail" :style="{ top: mheight + 'px' }">
			<view class="title">我的电梯</view>
			<view class="fitlerBox">
				<view class="left">
					<uni-search-bar class="uni-search-bar" v-model="searchForm.elevatorName" clearButton="auto"
						cancelButton="none" placeholder="请输入电梯关键字" @blurs="search" />
				</view>
				<view class="right">
					<filterModel :all="false" :buildingId="searchForm.buildingId" :userId="userinfo.user_id"
						ref="filterModel" :eltabIdx="eltabIdx" :tabIdx="tabIdx" :keyword="searchForm.elevatorName"
						:csd="csd" @filterd="filterd" :eleClassify="searchForm.eleClassify"
						@showFilterChange="showFilterChange">
					</filterModel>
				</view>
			</view>
			<view class="tab">
				<view class="tabBox" v-if="findRoute('depart_elevator')">
					<view v-for="(item, index) in ['部门管理电梯', '个人管理电梯']"
						:class="['tabItem', eltabIdx == index ? 'activeTabItem' : '']" @click="chooseDepart(index)"
						:key="index">
						<view class="name">
							{{ item }}
							<view class="line" v-if="eltabIdx == index"></view>
						</view>
					</view>
				</view>
				<view style="display: flex;padding: 20rpx 0;" v-if="eltabIdx != 0">
					<view v-for="(item, index) in ['全部', '责任梯', '维保电梯']"
						:class="['titleTab', tabIdx == index ? 'activeItem' : '']" @click="chooseTab(index)"
						:key="index">
						{{ item }}
					</view>
				</view>
			</view>
		</view>
		<tk-screen-scroll :list="['全部', '责任梯', '维保电梯']" @getActIdx="getActIdx" :height="240">
			<view class="total">共<view style="color: #0091FF;display: inline-block;">{{ orderEleTotal }}</view>台梯</view>
			<view class="detail_main">
				<view v-if="orderEleList && orderEleList.length > 0">
					<eleCard v-for="(e, i) in orderEleList" :key="i" :msg="e"
						:isLast="i == orderEleList.length - 1 ? true : false" @showChange="showChange"></eleCard>
				</view>
				<view class="empty" v-else>
					<view class="img">
						<image src="@/static/images/default.png"></image>
					</view>
					~暂无相关数据~
				</view>
			</view>
			<view class="more" v-if="orderEleTotal">- 已经到底了 -</view>
		</tk-screen-scroll>

		<!-- 筛选组件 -->
		<filterDrawer :isFilterList="projectMsg" :chooseData="choosed" :filterList="filterList"
			:comfireText="comfireText" :show="showFilter" :keyMap="keyMap" title="保养计划下载设置"
			mainTips="(请选择需要查看保养计划的时间范围)" ref="filter-drawer" :isMainPlan="true" :dateLists="dateLists"
			:orderType="orderType" :isShowDate="false" @closed="handleClose" @defaultReset="defaultReset"
			@customerOpenTime="customerOpenTime" @submit="submitFilter" @chooseTag="getResultCount"
			:countState="countState">
      <template v-slot:dateFilterBottom>
        <view class="begin-time" v-if="curValue===10 && (curStartDate || curEndDate)"><text>已选：</text><text>{{formatDisplayTime(curStartDate, curEndDate)}}</text></view>
      </template>
		</filterDrawer>
		<!-- 完成时间 -->
		<time-select v-if="selectTimePopup" :beforeToday="beforeToday" :atterToday="true" :isChooseToday="isChooseToday"
                 :default-model="timeSelectModel"
                 :default-select-time="defaultDate"
			@close="closeSelectTimePopup"></time-select>
		<!-- 电梯组件 -->
		<selectElevatorDet :depElevatorList="newOrderEleList" @changeTab="changeTab" @changeStatus="changeStatus"
			@chooseItem="chooseItem" ref="groupSelect" @submit="submit" @closedSele="closedSele" />
		<!-- 下载成功对话框 -->
		<model width="508rpx" :visible="successVisible" title="成功导出保养计划" cancleTxt="复制链接" comfireTxt="直接打开"
			@cancle="copyLink" @comfire="openFile">
			<view class="conte">
				<view class="modelItem"> 你可以直接打开，或者复制链接至 </view>
				<view class="modelItem"> 电脑端浏览器下载。 </view>
			</view>

		</model>

		<!-- 项目别名弹窗 -->
		<aliasPopup :showAlias="popupShowR" :aliasArr="aliasArr" @closedMask="closedMask"></aliasPopup>
		<previewMedia ref="previewMedia"></previewMedia>
	</view>
	<!-- <ui-container :isCanScroll="isCanScroll" :full="true" :scrollbar="false" :scrollGoTop="scrollGoTop"> --><!-- </ui-container> -->
</template>

<script>
import UiContainer from '@/components/ui-container/ui-container';
import eleCard from './components/eleCard.vue';
import { mapState, mapActions } from 'vuex';
import { projectDetail, myElevator, deptElevatorList } from '@/apis/project.js';
import { calendarPlan, calendarPlanExcel, calendarStatisticsCount } from '@/apis/maintains.js';
import { getNowTime, removeEmpty, hanleToken } from '@/utils/utils.js';
import filterModel from './components/elevatorFilter.vue';
import TkScreenScroll from '@/components/tk-screen-scroll/index';
import GlobalNavBar from '@/components/uni-nav-bar/global-nav-bar';
// import weekcalendar from "@/components/weekYearDate/week-calendar.vue"
import weekcalendar from '@/components/weekYearDate/rili.vue';

import filterDrawer from '@/components/filter-drawer/filterDrawer.vue';
import timeSelect from '@/pages/index/components/timeSelect.vue';
import selectElevatorDet from '../maintains/components/selectElevator.vue';
import model from '@/components/model/index.vue';
import dayjs from 'dayjs';
import aliasPopup from '@/components/card-dial/aliasPopup.vue';

export default {
	components: {
		GlobalNavBar,
		eleCard,
		filterModel,
		TkScreenScroll,
		UiContainer,
		weekcalendar,
		filterDrawer,
		timeSelect,
		selectElevatorDet,
		model,
		aliasPopup
	},
	data() {
		return {
			overflowShow: false,
			popupShow: false,
			mheight: 0,
			focusState: false, // 默认不获取焦点
			eltabIdx: 0,
			tabIdx: 0,
			projectMsg: {},
			searchForm: {
				elevatorName: '',  // 搜索
				buildingId: '',
				userId: '',
				useTypes: [], // 电梯类型
				modeIds: [], // 设备类型
				brandIds: [], // 品牌
				userId: [],
				size: 100,
			},
			orderEleList: [],
			orderEleTotal: 0,
			csd: {},

			excelURl: '',
			tempFilePath: '',
			list: [],
			elevatorIds: [],
			successVisible: false,
			selectTimePopup: false,
			showFilter: false,
			allChecked: true,
			choosed: {},
			chooseArr: [],
			filterList: [
				{ title: '按电梯查找', key: 'useTypes', tips: '请选择需要查看保养计划的电梯范围', list: [{ name: '全部电梯', value: 0 },] }
			],
			keyMap: {},
			orderType: 0,
			typeForm: 2,
			comfireText: '确定0个计划',
			dateObj: {
				startTime: '',
				endTime: '',
				planBeginDate: '',
				planEndDate: '',
				value: '',
				value2: ''
			},
			dateLists: [
				{ name: '今天', value: 1 },
				{ name: '本周', value: 2 },
				{ name: '本月', value: 3 },
				// { name: '后1个自然月', value: 4 },
				// { name: '后2个自然月', value: 5 },
				// { name: '后3个自然月', value: 6 },
				{ name: '下月', value: 4 },
				{ name: '后3个月', value: 7 },
				{ name: '后6个月', value: 8 },
				{ name: '本年', value: 9 },
				{ name: '自定义时间', value: 10 },
			],
			pageHight: uni.getSystemInfoSync().windowHeight,
			optionKey: '',// 日期组件key
			beforeToday: true,// 日期组件
			isChooseToday: true,// 日期组件

			depElevatorList: [],
			selectArr: [],// 选择的电梯
			monthArrs: {},// 周历数据
			eleAllIds: [],// 所有电梯id
			countState: 0,// 保养计划数量
			startDate: '',
			endDate: '',
			choosed1: [], // 部门单次电梯选择
			choosed2: [], // 个人 全部
			choosed3: [], // 个人 责任
			newOrderEleList: [],// 电梯选择数组
			curValue: 0,// 计划时间的value值
			curStartDate: '',// 自定义日期
			curEndDate: '',// 自定义日期
			startTimes: '',
			endTimes: '',
			popupShowR: false,
			aliasArr: [],
			// 时间选择组件模式
			timeSelectModel: 'date',
			defaultDate: [],
		};
	},
	created() {
		// uni.$on("getCustomerSwitch", (data, key) => {
		//   console.log('getCustomerSwitch', data, key)
		//   if (key == 'date-filter2') {
		//     this.beforeToday = true
		//   } else {
		//     this.beforeToday = false
		//   }
		//   this.optionKey = key
		//   this.selectTimePopup = data;

		// });
	},
	async onLoad(e) {
		console.log(e.id);
		this.searchForm.buildingId = e.id;
		this.searchForm.userId = this.userinfo.user_id;
		if (this.findRoute('depart_elevator')) {
			this.chooseDepart();
		} else {
			this.eltabIdx = 1;
			this.fetchList();
		}
		this.fetchBuildMsg();

		let result = await this.initElevatorAll(e.id);
		if (result && result.length) {
			// 默认加载月数据
			this.startDate = dayjs(new Date().getTime() - 1000 * 60 * 60 * 24).subtract(1, 'month').format('YYYY-MM-DD');
			this.endDate = dayjs(new Date().getTime() - 1000 * 60 * 60 * 24).add(1, 'month').format('YYYY-MM-DD');
			this.eleAllIds = result.map(item => item.elevatorId) || [];
			hanleToken('set', 'elevatorIdAll', this.eleAllIds);
			this.initPlanDateData(this.eleAllIds, this.startDate, this.endDate);
		}
	},
	computed: {
		...mapState('user', ['userinfo']),
	},
	onShow() {
		// 刷新部门管理电梯列表
		this.chooseDepart(0);
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
	onUnload() {
		hanleToken('remove', 'elevatorIdAll');
	},
	onHide() {
	},
	methods: {

		// 初始加载电梯
		initElevatorAll(buildingId) {
			let objs = {
				buildingId,
				size: 100,
				userId: this.userinfo.user_id,
			};
			let depMyIDs = [];
			return new Promise((resolve, reject) => {
				deptElevatorList(objs).then(res => {
					if (res.code === 200) {
						let arrs = res.data || [];
						arrs.map(item => {
							depMyIDs.push(item);
						});
						myElevator(objs).then(res => {
							if (res.code === 200) {
								let arr = res.data || [];
								arr.map(item => {
									depMyIDs.push(item);
								});
								resolve(depMyIDs);
							}
						});
					}
				});
			}).catch((err) => reject([]));
		},
		// 显示当前周
		todayClick() {
			this.initPlanDateData(this.eleAllIds, this.startDate, this.endDate, '');
		},
		// 显示当前年月
		resCurrYM() {
			// return {currentYear:this.$refs.weekcalendar.currentDateStr}
			return '2024-03-21';
		},
		// 切换周
		getRange(res) {
			let startTimes = res.starDate;
			let endTimes = res.endDate;
			this.startTimes = startTimes;
			this.endTimes = endTimes;
			let selectArr = this.selectArr && this.selectArr.length > 0 ? this.selectArr.map(item => item.elevatorId) : this.eleAllIds;
			this.initPlanDateData(selectArr, startTimes, endTimes);
		},
		pickDay(item) {
			console.log('pickDay', item);
			if (!item.elevatorCount) {
				uni.showToast({
					title: '该日期无保养计划',
					icon: 'none',
				});
				return;
			}
			let strTime = item.year + '-' + (item.month > 9 ? item.month : '0' + item.month) + '-' + (item.day > 9 ? item.day : '0' + item.day);
			let eleIds = [];
			if (this.selectArr && this.selectArr.length) {
				eleIds = this.selectArr.map(item => item.elevatorId);
			}
			uni.navigateTo({
				url: '/subpages/maintenanceStatistics/index?mainPlan=1' + '&planTimes=' + strTime + '&buildingId=' + this.searchForm.buildingId + '&eleIds=' + JSON.stringify(eleIds)
			});
		},
		// 初始加载日历排期数据
		initPlanDateData(elevatorIds = [], startDate, endDate, init = 'init') {
			// uni.showLoading({
			//   title: '加载中',
			//   icon: 'none'
			// });
			calendarPlan({
				elevatorIds,
				startDate,
				endDate
			}).then(res => {
				uni.hideLoading();
				if (res.code === 200) {
					// this.monthArrs = res.data || {}
					let objData = res.data || {};
					this.$refs.weekcalendar.init(objData, init);
				}
			}).catch(err => {
				// uni.hideLoading();
			});
		},
		// 选择电梯
		chooseItem({ choosed, tabIdx, statusActive, clearAll }) {
			if (tabIdx == 2) {
				this.choosed1 = choosed;
			}
			if (tabIdx == 1 && statusActive == 0) {
				this.choosed2 = choosed;
			}
			if (tabIdx == 1 && statusActive == 1) {
				this.choosed3 = choosed;
			}
			if (clearAll) {
				this.choosed1 = this.choosed2 = this.choosed3 = [];
			}
		},
		// 初始加载电梯
		initElevator(type, eleClassify = 0) {
			let objs = {
				buildingId: this.searchForm.buildingId,
				size: 100,
				userId: this.userinfo.user_id,
			};
			if (eleClassify) {// 个人责任梯区分参数
				objs.eleClassify = '0';
			}
			(type === 1 ? myElevator : deptElevatorList)(objs).then(res => {
				if (res.code === 200) {
					this.$nextTick(() => {
						this.newOrderEleList = res.data || [];
						this.newOrderEleList.forEach(item => {
							if (type == 2) {
								this.choosed1.forEach(it => {
									if (it.elevatorId == item.elevatorId) {
										item.choosed = true;
									}
								});
							}
							if (type == 1 && eleClassify == 0) {
								this.choosed2.forEach(it => {
									if (it.elevatorId == item.elevatorId) {
										item.choosed = true;
									}
								});
							}
							if (type == 1 && eleClassify == 1) {
								this.choosed3.forEach(it => {
									if (it.elevatorId == item.elevatorId) {
										item.choosed = true;
									}
								});
							}
						});
					});
				}
			});
		},
		// 电梯排期下载excel
		initElevatorExcel(elevatorIds, startDate, endDate, type) {
			uni.showLoading({
				title: '下载中',
				icon: 'none'
			});
			calendarPlanExcel({
				buildingId: this.searchForm.buildingId,
				elevatorIds,
				startDate,
				endDate,
				type
			}).then(res => {
				uni.hideLoading();
				this.successVisible = true;
				if (res.code === 200) {
					let excelURl = res.data || '';
					let str = excelURl.split('/')[excelURl.split('/').length - 1];
					this.excelURl = excelURl;
					// #ifdef h5
					uni.hideLoading();
					// #endif

					// #ifndef H5
					uni.downloadFile({
						url: res.data,
						filePath: wx.env.USER_DATA_PATH + '/' + str,
						success: (data) => {
							if (data.statusCode === 200) {
								// this.tempFilePath = data.tempFilePath;
								this.tempFilePath = data.filePath;
							}
						}, fail: (err) => {
							console.log(err, '下载失败');
						},
					});
					// #endif
				}
			});
		},
		openFile() {
			// #ifdef H5
			sida.openUrl({ url: this.excelURl });
			// #endif

			// #ifndef H5
			uni.openDocument({
				filePath: this.tempFilePath,
				showMenu: true,
				fileType: 'xlsx',
				success: (res) => {
					console.log('打开文档成功');
					this.successVisible = false;
				},
				fail: (err) => {
					console.log(err);
				}
			});
			// #endif
		},
		// 复制链接
		copyLink() {
			uni.setClipboardData({
				data: this.excelURl,
				success: (res) => {
					uni.getClipboardData({
						success(res) {
						},
					});
					this.successVisible = false;
				},
			});
		},
		// 部门个人梯切换
		changeTab(index) {
			this.initElevator(index,);
		},
		// 个人责任梯
		changeStatus(index) {
			this.initElevator(1, index);
		},
		submit(res) {
			console.log('submit', res);
			this.selectArr = res.selectArr;
			this.filterList[0].list[0].name = '全部电梯';
			let selectArr = this.selectArr && this.selectArr.length > 0 ? this.selectArr.map(item => item.elevatorId) : this.eleAllIds;
			if (this.selectArr && this.selectArr.length) {
				this.filterList[0].list[0].name = res.selectArr.length + '台电梯';
				let objs = { elevatorIds: selectArr, planBeginDate: this.curStartDate || '', planEndDate: this.curEndDate || '', cuValue: this.curValue || 3 };
				this.handleCount(objs);
			}

			this.initPlanDateData(selectArr, (this.startTimes || this.startDate), (this.endTimes || this.endDate));
		},

		// 完成筛选
		filterds(res) {
			let obj = JSON.parse(JSON.stringify(res.dateObj));
			if (obj.startTime && obj.startTime.indexOf(':') == -1) {
				obj.startTime = obj.startTime + ' 00:00:00';
			}
			if (obj.endTime && obj.endTime.indexOf(':') == -1) {
				obj.endTime = obj.endTime + ' 23:59:59';
			}

			if (obj.planBeginDate && obj.planBeginDate.indexOf(':') == -1) {
				obj.planBeginDate = obj.planBeginDate + ' 00:00:00';
			}
			if (obj.planEndDate && obj.planEndDate.indexOf(':') == -1) {
				obj.planEndDate = obj.planEndDate + ' 23:59:59';
			}
			let planBeginDate = '';
			let planEndDate = '';
			// 处理特殊类型：后6个月和本年
			if (obj.value2 === 8 || obj.value2 === 9) {
				const now = new Date();
				if (obj.value2 === 8) { // 后6个月
					// 从下月1日开始到6个月后的月末
					const startDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
					const endDate = new Date(now.getFullYear(), now.getMonth() + 7, 0);

					// 格式化日期
					planBeginDate = this.formatDate(startDate);
					planEndDate = this.formatDate(endDate);
				} else if (obj.value2 === 9) { // 本年
					// 本年1月1日到12月31日
					const startDate = new Date(now.getFullYear(), 0, 1);
					const endDate = new Date(now.getFullYear(), 11, 31);

					// 格式化日期
					planBeginDate = this.formatDate(startDate);
					planEndDate = this.formatDate(endDate);
				}
			} else {
				if (!obj.value2 || obj.value2 === 10) {
					obj.value2 = 7;
					planBeginDate = res.dateObj.planBeginDate;
					planEndDate = res.dateObj.planEndDate;
				}
			}
			if ([8,9,10].includes(res.cuValue)) {
				obj.value2 = 7;
			}
			let resArr = this.selectArr.length ? this.selectArr.map(item => item.elevatorId) : this.eleAllIds;
			this.initElevatorExcel(resArr, planBeginDate, planEndDate, obj.value2 - 1);
			this.initPlanDateData(resArr, this.startDate, this.endDate, '');
		},
		// 保存筛选
		submitFilter(res) {
			if (!this.countState) {
				return;
			}
			this.keyMap = res.keyMap;
			this.allChecked = res.allChecked;
			this.choosed = res.choosed;
			this.showFilter = false;
			// this.$refs['weekcalendar'].initData(new Date(),1)//初始
			this.filterds(res);
			this.$refs['groupSelect'].handleReset();// 初始
			this.$refs['filter-drawer'].mianPlanReset({});// 初始
			this.handleResetting();// 初始
		},
		// 弹窗后点击日期
		customerOpenTime(objs) {
			this.selectTimePopup = objs.isState;
		},
		// 清除
		handleClose() {
			this.curEndDate = '';
			this.curStartDate = '';
			this.defaultDate = [];
			this.timeSelectModel = 'date';
			this.showFilter = false;
			this.overflowShow = false;
			let obj = {};
			this.chooseArr.forEach(item => {
				if (obj[item.key]) {
					obj[item.key].push(item.value);
				} else {
					obj[item.key] = [];
					obj[item.key].push(item.value);
				}
			});
			this.choosed = obj;
		},
		// 点击标签的时候
		getResultCount(res) {
			if (res.cuValue) {
				this.curValue = res.cuValue;
			}
			if (res.choosed.useTypes && res.choosed.useTypes.length && res.hasOwnProperty('value')) {
				// this.$refs['filter-drawer'].choosed['useTypes'] = [0]
				this.selectElevator();
			} else {
				this.handleCount(res);
			}
		},

		// 自定义日期 --完成时间
		closeSelectTimePopup(res, model) {
			let start = '';
			let end = '';
			if (model) {
				this.timeSelectModel = model;
			}
			if (res) {
				console.log('自定义日期', res);
				if (res.indexOf('-') != -1) {
					const timeArr = res.split('-');
					start = timeArr[0].replaceAll('.', '-');
					end = timeArr[1].replaceAll('.', '-');
				} else {
					const time = res.replaceAll('.', '-');
					start = time;
					end = time;
				}
				const nowDay = getNowTime();
				let nowtime = new Date(nowDay).getTime();
				let starttime = new Date(start).getTime();
				let endtime = new Date(end).getTime();
				if (endtime >= nowtime && !this.beforeToday && !this.isChooseToday) {
					console.log('包含今天');
					uni.showToast({
						title: '自定义日期范围须小于今天',
						icon: 'none',
					});
					return;
				}
			} else {
			}
			if (start && end) {
				this.curStartDate = start;
				this.curEndDate = end;
				this.defaultDate = [start, end];
				uni.$emit('closeTimeSelectPlan', { start, end, value: 10 });// 向兄弟组件回显日期
				// let objs = { elevatorIds: this.selectArr && this.selectArr.length > 0 ? this.selectArr.map(item => item.elevatorId) : this.eleAllIds, planBeginDate: start, planEndDate: end, cuValue: 7 };
				// this.handleCount(objs);
			}
			this.selectTimePopup = false;
		},
		// 选择梯
		selectElevator() {
			this.overflowShow = true;
			let res = {
				detail: {
					value: ''
				}
			};
			if (this.findRoute('depart_elevator')) {
				this.initElevator(2,);
			} else if (this.findRoute('personal_elevator')) {
				this.initElevator(1,);
			}
			this.$refs.groupSelect.searchFuc(res);
			this.$refs.groupSelect.showDrawer = true;
		},
		// 关闭电梯组件
		closedSele() {
			this.overflowShow = false;
			console.log('关闭电梯组件', this.$refs.groupSelect);
		},
		// 打开下载弹窗
		selectDown() {
			this.overflowShow = true;
			this.showFilter = true;
			this.curEndDate = '';
			this.curStartDate = '';
			this.defaultDate = [];
			this.timeSelectModel = 'date';
			let objs = {
				elevatorIds: this.selectArr && this.selectArr.length > 0 ? this.selectArr.map(item => item.elevatorId) : this.eleAllIds,
				planBeginDate: this.startDate, planEndDate: this.endDate, cuValue: 3
			};
			this.handleCount(objs);
			this.$nextTick(() => {
				this.$refs['filter-drawer'].choosed['useTypes'] = [0];
				this.$refs['filter-drawer'].defaultPlan({ value: 3 });
			});
		},

		toPlanDetail() {
			uni.navigateTo({
				url: '/pageModules/maintains/maintainsPlan?buildingId=' + this.searchForm.buildingId + '&name=' + this.projectMsg.name
			});
		},
		handleResetting() {
			this.comfireText = '确定0个计划';
			this.countState = 0;
			this.selectArr = [];
			this.filterList[0].list[0].name = '全部电梯';
			this.$refs['filter-drawer'].choosed['useTypes'] = [0];
			// this.$refs['groupSelect'].handleReset()
			this.$refs['filter-drawer'].mianPlanReset({ key: 'useTypes', value: 0 });
			this.$refs['filter-drawer'].defaultPlan({ value: 3 });
		},
		// 重置默认
		defaultReset() {
			// this.comfireText = `确定0个计划`;
			// this.countState = 0
			this.curEndDate = '';
			this.curStartDate = '';
			this.defaultDate = [];
			this.timeSelectModel = 'date';
			this.selectArr = [];
			this.filterList[0].list[0].name = '全部电梯';
			this.$refs['groupSelect'].handleReset();
			this.$refs['filter-drawer'].mianPlanReset({ key: 'useTypes', value: 0 });
			this.$refs['filter-drawer'].defaultPlan({ value: 3 });
			let objs = { elevatorIds: this.selectArr && this.selectArr.length > 0 ? this.selectArr.map(item => item.elevatorId) : this.eleAllIds, planBeginDate: '', planEndDate: '', cuValue: 3 };
			this.handleCount(objs);
		},
		// 获取点击筛选条件后的数量总数	
		async handleCount(res) {
			const { allChecked, choosed, reset, cuValue } = res;
			if (reset) {
				this.handleResetting();
				return;
			}
			if (!cuValue) {
				this.comfireText = '确定0个计划';
				this.countState = 0;
				return;
			}

			let startDate = res.planBeginDate;
			let endDate = res.planEndDate;

			// 处理特殊日期类型：后6个月和本年
			if (cuValue === 8 || cuValue === 9) {
				const now = new Date();
				if (cuValue === 8) { // 后6个月
					// 从下月1日开始到6个月后的月末
					const startDateObj = new Date(now.getFullYear(), now.getMonth() + 1, 1);
					const endDateObj = new Date(now.getFullYear(), now.getMonth() + 7, 0);

					// 格式化日期
					startDate = this.formatDate(startDateObj);
					endDate = this.formatDate(endDateObj);

					// 更新curStartDate和curEndDate用于显示
					this.curStartDate = this.formatDate(startDateObj);
					this.curEndDate = this.formatDate(endDateObj);
				} else if (cuValue === 9) { // 本年
					// 本年1月1日到12月31日
					const startDateObj = new Date(now.getFullYear(), 0, 1);
					const endDateObj = new Date(now.getFullYear(), 11, 31);

					// 格式化日期
					startDate = this.formatDate(startDateObj);
					endDate = this.formatDate(endDateObj);

					// 更新curStartDate和curEndDate用于显示
					this.curStartDate = this.formatDate(startDateObj);
					this.curEndDate = this.formatDate(endDateObj);
				}
			}
			let type = res.cuValue - 1 || 0;
			if ([8,9,10].includes(res.cuValue)) {
				type = 6;
			}
			let params = {
				elevatorIds: this.selectArr && this.selectArr.length > 0 ? this.selectArr.map(item => item.elevatorId) : this.eleAllIds,
				startDate: startDate,
				endDate: endDate,
				// 日期选择的类型
				type: type,
			};
			if (Object.keys(res).length) {
				// let resultObjs = removeEmpty(params)
				let count = await this.handleGetCount(params);
				this.countState = count;
				if (count > 0) {
					this.comfireText = `确定${count}个计划`;
				} else {
					uni.showToast({
						icon: 'none',
						title: '筛选结果为空 请重新选择条件'
					});
					this.countState = 0;
					this.comfireText = '确定0个计划';
				}
			}
		},
		// 获取计划数量
		handleGetCount(objs) {
			return new Promise((resolve, reject) => {
				calendarStatisticsCount(objs).then(res => {
					if (res.code === 200) {
						let arrs = res.data || [];
						resolve(arrs);
					}
				});
			}).catch((err) => reject([]));
		},

		// 失去光标
		blur() {
			this.clearBool = false;
			this.search();
		},
		// 搜索
		search() {
			if (this.eltabIdx == 1) {
				this.fetchList();
			} else {
				this.chooseDepart();
			}
		},
		setHeight(n) {
			this.mheight = n;
		},
		showChange(data) {
			this.popupShow = data;
		},
		// 返回顶部
		backTop() {
			if (this.scrollTop != 0) {
				uni.pageScrollTo({
					scrollTop: 0
				});
			}
		},
		showFilterChange(res) {
			// this.isCanScroll = !res;
		},
		getActIdx(idx) {
			if (this.eltabIdx == 0 || this.popupShow) return;
			this.tabIdx = idx;
			this.searchForm.elevatorName = '';
			this.searchForm.brandIds = [];
			this.searchForm.useTypes = [];
			this.searchForm.modeIds = [];
			switch (idx) {
			case 0:
				this.searchForm.eleClassify = '';
				break;
			case 1:
				this.searchForm.eleClassify = '0';
				break;
			case 2:
				this.searchForm.eleClassify = '1';
				break;
			}
			this.backTop();
			this.fetchList();
		},
		getAliasStr(str) {
			if (!str) {
				return '';
			}
			if (str.length > 20) {
				return '(项目别名：' + str.slice(0, 20) + '...)';
			} else {
				return '(项目别名：' + str + ')';
			}
		},
		toAddress({ latitude, longitude, name, buildingExt, address }) {
			let aliasesName =
				buildingExt.relationAliases == null
					? ''
					: buildingExt.relationAliases
						.map((item) => {
							return item.alias;
						})
						.join(',');

			uni.openLocation({
				latitude: Number(latitude),
				longitude: Number(longitude),
				name: name + this.getAliasStr(aliasesName),
				scale: 18,
				address,
			});
		},

		// 筛选 获取数据
		filterd(res) {
			let { useTypes, modeIds, brandIds } = res.choosed;
			this.csd = res.choosed;
			let keys = Object.keys(res.choosed);
			if (keys.length) {
				if (useTypes && useTypes.length) {
					this.searchForm.useTypes = res.choosed.useTypes;
				}
				if (modeIds && modeIds.length) {
					this.searchForm.modeIds = res.choosed.modeIds;
				}
				if (brandIds && brandIds.length) {
					this.searchForm.brandIds = res.choosed.brandIds;
				}
			} else {
				this.searchForm.brandIds = [];
				this.searchForm.useTypes = [];
				this.searchForm.modeIds = [];
			}
			this.search();
		},
		// 项目详情页面
		toProjectDetail() {
			uni.navigateTo({
				url: `/pageModules/projectInfo/index?id=${this.searchForm.buildingId}&type=0`,
			});
		},
		chooseTab(res) {
			this.tabIdx = res;
			this.searchForm.elevatorName = '';
			this.searchForm.brandIds = [];
			this.searchForm.useTypes = [];
			this.searchForm.modeIds = [];
			this.backTop();
			switch (res) {
			case 0:
				this.searchForm.eleClassify = '';
				break;
			case 1:
				this.searchForm.eleClassify = '0';
				break;
			case 2:
				this.searchForm.eleClassify = '1';
				break;
			}
			this.fetchList();
		},
		// 获取头部项目信息
		fetchBuildMsg() {
			uni.showLoading({
				title: '加载中',
				mask: true,
			});
			projectDetail({ buildingId: this.searchForm.buildingId }).then((res) => {
				this.projectMsg = res.data || {};
				uni.hideLoading();
			}).catch(err => {
				uni.hideLoading();
			});
		},
		// 获取列表数据
		fetchList() {
			// this.searchForm.userId=this.userinfo.user_id
			myElevator(removeEmpty(this.searchForm)).then((res) => {
				if (res) {
					this.orderEleList = res.data || [];
					this.orderEleList.forEach(e => {
						if (e.realNames && e.phones) {
							let realNames = e.realNames.split(',');
							let phones = e.phones.split(',');
							e.mantles = realNames.map((realNames, i) => ({ realNames, phones: phones[i] }));
						}
					});
					// if(this.orderEleList.length){
					//   this.initPlanDateData(this.orderEleList.map(item=>item.elevatorId),"2023-06-01","2023-06-07")
					// }

					this.orderEleTotal = res.data.length;
					if (this.orderEleList.length == 0) {
						this.backTop();
					}
				}
			});
		},
		// 个人、部门管理切换
		chooseDepart(index) {
			if (index != null) {
				this.eltabIdx = index;
				this.tabIdx = 0;
				this.searchForm.brandIds = [];
				this.searchForm.useTypes = [];
				this.searchForm.modeIds = [];
			}
			this.backTop();
			if (this.eltabIdx == 0) {
				this.searchForm.eleClassify = '';
				deptElevatorList(removeEmpty(this.searchForm)).then(res => {
					this.orderEleList = res.data;
					this.orderEleList.forEach(e => {
						if (e.realNames && e.phones) {
							let realNames = e.realNames.split(',');
							let phones = e.phones.split(',');
							e.mantles = realNames.map((realNames, i) => ({ realNames, phones: phones[i] }));
						}
					});
					// if(this.orderEleList.length){
					//   this.initPlanDateData(this.orderEleList.map(item=>item.elevatorId),"2023-06-01","2023-06-07")
					// }
					this.orderEleTotal = res.data.length;
				});
			} else {
				// this.tabIdx = 0
				// this.searchForm.eleClassify = "";
				this.fetchList();
			}
		},

		// 项目别名弹窗
		petName(obj) {
			this.popupShowR = true;
			this.overflowShow = true;
			this.aliasArr = (obj.relationAliases || []).map(item => item.alias);
		},
		closedMask(show) {
			this.overflowShow = false;
			this.popupShowR = false;
		},
		// 格式化日期的辅助方法
		formatDate(date) {
			const year = date.getFullYear();
			const month = (date.getMonth() + 1).toString().padStart(2, '0');
			const day = date.getDate().toString().padStart(2, '0');
			return `${year}-${month}-${day}`;
		},
		// 格式化显示时间
		formatDisplayTime(start, end) {
			if (!start || !end) return '';

			// 解析日期
			const startDate = new Date(start.replace(/\//g, '-'));
			const endDate = new Date(end.replace(/\//g, '-'));

			const startYear = startDate.getFullYear();
			const startMonth = (startDate.getMonth() + 1).toString().padStart(2, '0');
			const endYear = endDate.getFullYear();
			const endMonth = (endDate.getMonth() + 1).toString().padStart(2, '0');

			// 检查是否跨年度
			if (this.timeSelectModel === 'year') {
				if (startYear === endYear) {
					return `${startYear}`;
				}
				return `${startYear}，${endYear}`;
			}
			// if (startYear !== endYear) {
			// 	return `${startYear}，${endYear}`;
			// }

			// 检查是否为月份的第一天和最后一天
			// const isMonthStart = startDate.getDate() === 1;
			// const isMonthEnd = endDate.getDate() === new Date(endYear, endDate.getMonth() + 1, 0).getDate();
			//
			// 如果是月份的开始和结束，显示年-月格式
			// if (isMonthStart && isMonthEnd &&
			// 	(endDate.getMonth() - startDate.getMonth() > 0 || endYear > startYear)) {
			// 	return `${startYear}-${startMonth}至${endYear}-${endMonth}`;
			// }
			if (this.timeSelectModel === 'month') {
				if (startYear === endYear && startMonth === endMonth) {
					return `${startYear}-${startMonth}`;
				}
				return `${startYear}-${startMonth}至${endYear}-${endMonth}`;
			}
			// 默认显示原始格式
			return `${start}至${end}`;
		},
	},
};
</script>
<style>
page {}
</style>
<style lang="scss" scoped>
.conte {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	margin: 0rpx 0 40rpx 0;

	.modelItem {
		font-size: 28rpx;
		color: #333333;
	}
}

.taskCard {
	background: #ffffff;
	border-radius: 8rpx;
	// padding: 20rpx;
	margin-bottom: 20rpx;

	.topTitles {
		font-size: 32rpx;
		color: #333;
		font-weight: 600;
		padding: 20rpx 0 0 20rpx;
	}

	.top {
		padding: 26rpx 24rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 2rpx solid #e9e9e9;
		position: relative;

		.topTitle {
			font-size: 26rpx;
			color: #666666;

			text:nth-of-type(1) {
				color: #333333;
				vertical-align: middle;
			}

			image {
				width: 32rpx;
				height: 32rpx;
				margin-right: 4rpx;
				margin-left: 5rpx;
				vertical-align: middle;
			}

			text:nth-of-type(2) {
				vertical-align: middle;
			}
		}

		.topRight {
			display: flex;
			align-items: center;

			image {
				width: 32rpx;
				height: 32rpx;
				margin-right: 4rpx;
			}
		}

		.line {
			width: 710rpx;
			height: 2rpx;
			background: #e9e9e9;
			position: absolute;
			bottom: 0;
			left: 0;
		}

		.subLeft {
			width: 2rpx;
			height: 30rpx;
			background: #ccc;
			margin: 0 26rpx;
		}

		.subTitle,
		.allTask {
			color: #999;
			font-size: 24rpx;
		}

		.subTitle {
			font-size: 26rpx;
			color: #666666;
			display: flex;
			align-items: center;
		}
	}

	.cardContent {
		display: flex;
		// padding: 10rpx 0 0 0;

		.cardContent_left {
			display: flex;
			flex: 1;
			height: 180rpx;
		}

		.showdown {
			width: 12rpx;
			// height: 218rpx;
			background: linear-gradient(-90deg,
					rgba(51, 51, 51, 0.14),
					rgba(255, 255, 255, 0));
		}

		.cardContent_right {
			image {
				width: 32rpx;
				height: 32rpx;
			}

			display: flex;
			width: 62rpx;
			background: #ffffff;
			border-radius: 0rpx 0rpx 16rpx 0rpx;
			flex-direction: column;
			color: #666;
			justify-content: center;
			align-items: center;
			font-size: 24rpx;
		}
	}
}

.navBarTop {
	position: sticky;
	top: 0;
	left: 0;
	z-index: 300;
}

.projectDetail {
	background: #f3f6f8;

	.empty {
		display: flex;
		align-items: center;
		justify-content: center;

		image {
			width: 64rpx;
			height: 64rpx;
		}

		height: 600rpx;
		flex-direction: column;
	}

	.header {
		background: #f3f6f8;

		.header_content {
			padding: 34rpx 20rpx 20rpx 28rpx;
			background: #fff;
			margin-bottom: 20rpx;

			.top {
				display: flex;
				justify-content: space-between;
				position: relative;

				.left {
					display: flex;

					.title {
						font-size: 32rpx;
						font-weight: 600;
						color: #333;
						width: 560rpx;

						.buildAddress {
							font-size: 24rpx;
							color: #999;
							font-weight: 400;

							.buildings {
								overflow: hidden;
								text-overflow: ellipsis;
								white-space: nowrap;
								max-width: 550rpx;
								color: #666;
								font-size: 20rpx;
							}
						}

						text {
							font-weight: normal;
							color: #999;
							font-size: 24rpx;
						}
					}

					image {
						width: 48rpx;
						height: 48rpx;
						margin-right: 12rpx;
					}
				}

				.right {
					color: #666;
					font-size: 24rpx;
					display: flex;
					position: absolute;
					right: 0;
					top: 8rpx;

					image {
						width: 28rpx;
						height: 28rpx;
						margin-right: 4rpx;
					}
				}
			}

			.msg {
				display: flex;
				font-size: 24rpx;
				margin-top: 32rpx;

				image {
					width: 32rpx;
					height: 32rpx;
				}

				.left {
					width: 296rpx;
					display: flex;
					padding-left: 60rpx;
					box-sizing: border-box;
					position: relative;

					.line {
						width: 2rpx;
						height: 24rpx;
						background-color: #ccc;
						position: absolute;
						right: 0;
						top: 4rpx;
					}
				}

				.right {
					display: flex;
					flex: 1;
					justify-content: space-between;
					padding-left: 20rpx;

					.more {
						margin: 0;
						color: #0091ff;
					}
				}
			}
		}
	}

	.tab_detail {
		background: #ffffff;
		border-radius: 8rpx;
		padding: 20rpx;
		padding-bottom: 0;
		position: sticky;
		top: 0;
		left: 0;
		z-index: 10;

		.title {
			font-size: 32rpx;
			color: #333;
			font-weight: 600;
			margin-bottom: 20rpx;
		}

		.searchBoxt {
			display: flex;
		}

		.tab {
			// display: flex;
			// border-bottom: 2rpx solid #eeeeee;
			// padding-top: 32rpx;

			.titleTab {
				height: 44rpx;
				border-radius: 22rpx;
				padding: 0 20rpx;
				margin-left: 20rpx;
				background-color: #F3F6F8;
				color: #666;
				font-size: 26rpx;
				line-height: 44rpx;
			}

			.tabItem {
				width: 30%;
				display: flex;
				font-size: 26rpx;
				color: #93b1c7;
				cursor: pointer;
				margin-left: 10px;

				.name {
					position: relative;
					height: 42rpx;
				}

				.line {
					height: 4rpx;
					background: #0091ff;
					position: absolute;
					left: 0;
					top: 60rpx;
					width: 100%;
				}
			}

			.activeItem {
				background-color: #DCF0FF;
				color: #0091FF;
				font-size: 26rpx;
			}

			.activeTabItem {
				font-size: 30rpx;
				font-weight: bold;
				color: #0091ff;
			}
		}

		.tabBox {
			display: flex;
			margin-right: -20rpx;
			margin-left: -20rpx;
			padding: 20rpx;
			padding-right: 0;
			border-bottom: 1px solid #eeeeee;
		}

		.fitlerBox {
			// height: 96rpx;
			background: #ffffff;
			display: flex;
			align-items: center;

			// padding: 16rpx 20rpx;
			.left {
				width: 570rpx;
				height: 64rpx;
				box-sizing: border-box;
				background: #f6f6f6;
				border-radius: 8rpx;
				display: flex;
				align-items: center;

				.uni-search-bar {
					/deep/ .uni-searchbar {
						padding: 0;
					}

					/deep/ .uni-searchbar__box {
						width: 600rpx;
						height: 64rpx;
						justify-content: flex-start;
						font-size: 26rpx;
						color: #ccc;
						background-color: #f6f6f6;
						border: 0;
						border-radius: 8rpx;
					}

					/deep/ .uni-icons {
						width: 40rpx;
						height: 40rpx;
					}

					/deep/ .uni-searchbar__text-placeholder {
						margin: 0;
					}

					/deep/ .uni-searchbar__box-search-input {
						border: 0;
						padding: 0;
					}
				}

				image {
					width: 40rpx;
					height: 40rpx;
				}
			}

			.right {
				display: flex;
				flex: 1;
				align-items: center;
				font-size: 26rpx;
				color: #333;
				justify-content: flex-end;

				image {
					width: 26rpx;
					height: 26rpx;
				}
			}
		}
	}

	.detail_main {
		// width: 710rpx;
		// height: 1458rpx;
		background: #ffffff;
		border-radius: 8rpx;
		margin: 0 20rpx;
		margin-top: 20rpx;
		padding: 20rpx;
		padding-top: 0;
		// margin-bottom: 62rpx;
		// background: pink;
		// min-height: 700rpx;

	}

	.more {
		color: #999;
		margin-top: 16rpx;
		margin-bottom: 16rpx;
		text-align: center;
	}

	.total {
		margin-top: 20rpx;
		padding-left: 40rpx;
		font-size: 24rpx;
		color: #999999;
	}
}
.begin-time{
  padding: 16rpx 0;
  color: #333333;
  &>text:first-child{
    color: #666666;
  }
}
.overflow{
  height: 100vh;
  overflow-y: hidden;
}
</style>